#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
    int bagOfTokensScore(vector<int>& tokens, int P) {
        sort(tokens.begin(), tokens.end());
        int begin = 0, end = tokens.size()-1;
        int score = 0;
        int res = 0;
        while (begin <= end) {
            while (begin<=end&&tokens[begin] <= P) {
                P -= tokens[begin++];
                ++score;
            }
            res = max(res, score);
            while (begin <= end&&tokens[begin]>P) {
                P += tokens[end--];
                if (score < 1) {
                    begin = end + 1;
                    break;
                }
                --score;
            }
        }
        return res;
    }
};